<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
    <jsp:include page="../inc/js.jsp"/>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>文章管理</title>
    <jsp:include page="../inc/css.jsp"/>
    <!-- 1. 引入 TinyMCE（离线包或 CDN 均可） -->
    <script src="static/tinymce/tinymce.min.js" referrerpolicy="origin"></script>
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">
    <jsp:include page="../inc/menu.jsp"/>

    <div class="content-wrapper">
        <section class="content">
            <div class="row">
                <div class="col-12">
                    <div class="card" style="margin-top: 10px">
                        <div class="card-header">
                            <div class="form-inline">
                                <button type="button" title="保存" class="btn btn-info" onclick="_articleInfo.fn.saveInfo()">保存</button>
                                <button type="button" title="返回列表" class="btn btn-warning tableTopBtn" onclick="_articleInfo.fn.goBack()">返回</button>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <!-- 3. 表单 -->
                                <form id="articleForm" method="post">
                                    <input type="hidden" id="hiddenArticleId" value="${article.id}">

                                    <!-- 一行两栏：input + select -->
                                    <div class="form-row" style="margin: 0 0 10px 0;">
                                        <!-- 左边输入框 -->
                                        <div class="col-md-10">
                                            <input type="text" name="articleTitle" value="${article.title}" placeholder="请在此输入文章标题" maxlength="50" class="form-control" required style="padding-left: 15px;padding-right: 15px;">
                                        </div>

                                        <!-- 右边下拉框 -->
                                        <div class="col-md-2">
                                            <select id="typeList" class="form-control">
                                                <option value="1">公告提醒</option>
                                                <option value="2">设备宣传</option>
                                            </select>
                                        </div>
                                    </div>

                                    <textarea id="articleContent" name="content">${article.articleContent}</textarea>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </div>
</div>
<!-- ./wrapper -->

<!-- page script -->
<script type="text/javascript">
    let _articleInfo = {
        v: {
            tinymce: null
        },
        fn: {
            goBack: function () {
                window.history.go(-1);
            },
            saveInfo: function () {
                let title = $('input[name=articleTitle]').val().trim();
                let content = _articleInfo.v.tinymce.getContent().trim();
                let avatar = '';

                if (!title) {
                    info('文章标题不能为空', 'error');
                    return;
                }
                if (!content) {
                    info('文章内容不能为空', 'error');
                    return;
                }

                // 匹配 <img src="xxx"> 里的 xxx
                const imgReg = /<img[^>]+src\s*=\s*['"]([^'"]+)['"][^>]*>/gi;
                let urls = [];
                let match;

                while ((match = imgReg.exec(content)) !== null)
                    urls.push(match[1]);   // match[1] 就是纯 URL

                if (urls.length > 0) avatar = urls[0];

                startLoading();

                $.post('backend/article/save', {
                    id: $('#hiddenArticleId').val(),
                    type: $('#typeList').val(),
                    avatar: avatar,
                    title: title,
                    content: content
                }, function (r) {
                    endLoading();

                    info(r.msg || '保存成功', r.code === 0 ? 'success' : 'error');
                });
            }
        }
    };

    $(document).ready(function () {
        _articleInfo.v.tinymce = tinymce.init({
            selector: '#articleContent',
            license_key: 'gpl',   // ← 关键行，声明遵守 GPLv2+
            promotion: false,          // ← 关闭所有“升级”提示
            statusbar: false,   // 整个状态栏隐藏 → 右下角文字一起消失
            language: 'zh_CN',
            height: 600,
            plugins: [
                'advlist', 'autolink', 'link', 'image', 'lists', 'charmap', 'preview', 'anchor', 'pagebreak',
                'searchreplace', 'fullscreen', 'insertdatetime', 'media', 'table', 'help'
            ],
            toolbar: 'undo redo | bold italic backcolor | ' +
                'alignleft aligncenter alignright alignjustify | ' +
                'bullist numlist outdent indent | link image | code | help',
            // 关键：图片上传逻辑
            images_upload_handler: (blobInfo, progress) => {
                // 1. 返回 Promise
                return new Promise((resolve, reject) => {
                    const formData = new FormData();
                    formData.append('file', blobInfo.blob(), blobInfo.filename());

                    fetch('http://58.51.194.169:8004/api/upload', {
                        method: 'POST',
                        body: formData
                    })
                        .then(res => {
                            if (!res.ok) throw new Error('上传失败');
                            return res.text();   // 你的接口返回纯 URL
                        })
                        .then(url => resolve(url)) // 2. 成功 -> resolve(图片地址)
                        .catch(err => reject(err.message)); // 3. 失败 -> reject
                });
            },
            /* 上传额外参数（可选） */
            images_upload_credentials: true,
            setup: function (ed) {
                /* 关键：初始化完成后再把实例存到全局变量 */
                ed.on('init', function () {
                    _articleInfo.v.tinymce = ed;   // 此时 ed 就是可用的编辑器对象
                });
            }
        });

        window.onload = function () {
            checkSelectMenu("articleLi");

            loadMenuColor('articleLi');
        };
    });
</script>
</body>
</html>